package com.yiyun.blog.admin.service;

import com.yiyun.blog.admin.pojo.Admin;
import com.yiyun.blog.admin.pojo.Permission;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author Bao
 * @create 2022-05-12-15:01
 *
 * 权限认证
 */
@Service
public class AuthService {

    @Autowired
    private AdminService adminService;

    public boolean auth(HttpServletRequest request, Authentication authentication){
        // 请求路径 anonymousUser：匿名用户
        String requestURI = request.getRequestURI();
        Object principal = authentication.getPrincipal();
        if (principal == null || "anonymousUser".equals(principal)){
            // 未登录
            return false;
        }
        UserDetails userDetails = (UserDetails)principal;
        String username = userDetails.getUsername();
        Admin admin = adminService.findAdminByUsername(username);
        if (admin == null){
            return  false;
        }
        if (admin.getId()==1){
            //  超级管理员
            return true;
        }
        Long adminId = admin.getId();
        requestURI = StringUtils.split(requestURI,'?')[0];
        List<Permission> permissionList = adminService.findPermissionByAdminId(adminId);
        for (Permission permission : permissionList) {
            if (requestURI.equals(permission.getPath())){
                return true;
            }
        }
        return false;
    }
}
